package com.csw.controller;

import com.csw.entity.Dir;
import com.csw.entity.TiaoZhuan;
import com.csw.entity.User;
import com.csw.service.DirService;
import com.csw.service.FileService;
import com.csw.util.DeleteAllByPath;
import com.csw.util.MD5Utils;
import com.csw.util.ObjectIdUtil;
import com.csw.util.TextCopyFileAndMove;
import com.csw.util.ZipUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipOutputStream;

@RequestMapping("mydoc")
@RestController
public class MyDocController {
    @Autowired
    private FileService fileService;

    @Autowired
    private DirService dirService;

    /**
     * @param did
     * @param session
     * @return
     */
    @RequestMapping("queryOne")
    public String queryOne(String did, HttpSession session, String inSearchName) {

            String dirYd = (String) session.getAttribute("DirYd");
            User user = (User) session.getAttribute("user");
            if (user == null) {
                session.setAttribute("message", "用户不存在，退出登录");
                return "redirect:/user/logOut";
            }
            int status = 1;
            List<Dir> dirs;
            List<com.csw.entity.File> files;
            if (did != null) {
                if (did.equals("shouye")) {
                    List<TiaoZhuan> tiaoZhuanList = new ArrayList<>();
                    session.setAttribute("tzList", tiaoZhuanList);
                    String uid = user.getId();
                    String pid = null;
                    Dir dir = dirService.queryFistDir(uid, pid, status);
                    String firstDid = dir.getId();
                    if (dirYd == null) {
                        dirs = dirService.queryAllById(firstDid, user, status);
                    } else {
                        dirs = dirService.queryAllByIddirYd(firstDid, user, status, dirYd);
                    }
                    files = fileService.queryAllById(firstDid, user, status);
                    session.setAttribute("did", firstDid);
                } else {
                    List<TiaoZhuan> tzList = (List<TiaoZhuan>) session.getAttribute("tzList");

                    if (dirYd == null) {
                        dirs = dirService.queryAllById(did, user, status);
                    } else {
                        dirs = dirService.queryAllByIddirYd(did, user, status, dirYd);
                    }
                    files = fileService.queryAllById(did, user, status);
                    session.setAttribute("did", did);
                    /**/
                    boolean judge = false;
                    for (TiaoZhuan tz : tzList) {
                        if (tz.getId().equals(did)) {
                            judge = true;
                        }
                    }
                    if (!judge) {
                        Dir dir = dirService.selectById(did);
                        tzList.add(new TiaoZhuan(did, dir.getName()));
                    } else {
                        List<TiaoZhuan> tiaoZhuanList = new ArrayList<>();
                        for (TiaoZhuan tz : tzList) {
                            tiaoZhuanList.add(tz);
                            if (tz.getId().equals(did)) {
                                break;
                            }

                        }
                        tzList = tiaoZhuanList;
                    }
                }

            } else {
                String did1 = (String) session.getAttribute("did");
                if (dirYd == null) {
                    dirs = dirService.queryAllById(did1, user, status);
                } else {
                    dirs = dirService.queryAllByIddirYd(did1, user, status, dirYd);
                }
                files = fileService.queryAllById(did1, user, status);
            }
            //图片路径
            List<String> stringList = new ArrayList<>();
            for (com.csw.entity.File file : files) {
                String path = file.getPath() + "\\" + file.getNewName();
                stringList.add(path);
            }
            session.setAttribute("stringList", stringList);
            session.setAttribute("dirs", dirs);
            session.setAttribute("files", files);
            //查询完成
            return "redirect:/jsp/front/main/detail/mydoc.jsp";


    }

    /*首先查询所有，点击首页和点击个人中心查询到的都是一样的,点击每个文件夹相当于 相当于一次查询
    ，每次查询都要把最近的父文件夹id放到session中，查询的时候如何点击的是文件的，不做任何变化，
    如果是文件夹，则要查询所有，并且更新id*/

    /**
     * @param fileName
     * @param session
     * @return
     */
    @RequestMapping("addDir")
    public String addDir(String fileName, HttpSession session) {

            if (fileName == null) {
            } else {

                String did = (String) session.getAttribute("did");
                Dir dir = dirService.selectById(did);
                Dir dir3 = dirService.queryByPidAndName(did, fileName);
                if (dir3 != null) {
                    session.setAttribute("message", "有相同目录不能再次添加");
                } else {
                    User user = (User) session.getAttribute("user");
                    String path = dir.getPath() + "\\" + dir.getName();

                    Dir dir1 = new Dir();
                    dir1.setId(ObjectIdUtil.getObjectId());
                    dir1.setName(fileName);
                    dir1.setPath(path);
                    dir1.setCount(0);
                    dir1.setCreateTime(new Date());
                    dir1.setStatus(1);
                    dir1.setIsShare(0);
                    dir1.setIcon("文件夹");
                    dir1.setDid(dir.getId());
                    dir1.setUser(user);
                    //创建用户目录dir1
                    dirService.addRootDir(dir1);
                    //本地创建
                    File folder = new File(path + "\\" + fileName);
                    if (!folder.exists()) {
                        folder.mkdirs();
                    }
                }
            }
            return "redirect:/mydoc/queryOne";

    }

    /**
     * @param files
     * @param session
     * @return
     */
    @RequestMapping("uploaddir")
    public String upload(MultipartFile[] files, HttpSession session) throws Exception {

            String did = (String) session.getAttribute("did");
            Dir dir = dirService.selectById(did);
            String path0 = dir.getPath() + "\\" + dir.getName();
            User user = (User) session.getAttribute("user");

            for (MultipartFile aa : files) {
                String prepath = aa.getOriginalFilename();
                if (prepath.equals("")) {
                    return "redirect:/mydoc/queryOne";
                }
                assert prepath != null;
                //包含文件夹名称和文件名称的数组
                String[] stringPath = prepath.split("/");
                for (int i = 0; i <= stringPath.length - 1; i++) {
                    //i全是文件夹
                    if (i != stringPath.length - 1) {
                        //不是最后一个文件
                        StringBuilder path = new StringBuilder(path0);
                        for (int j = 0; j <= i; j++) {
                            //j全是文件夹
                            //下面进行判断操作stringPath
                            //根据路径和名字查询文件夹是否存在
                            Dir dir1 = dirService.selectDirPath(path.toString(), stringPath[j]);
                            if (dir1 != null) {
                                //这个文件夹存在
                            } else {
                                //这个文件夹不存在，创建一个新的文件夹
                                Dir dir2 = new Dir();
                                dir2.setId(ObjectIdUtil.getObjectId());
                                dir2.setName(stringPath[i]);
                                dir2.setPath(path.toString());
                                dir2.setCount(0);
                                dir2.setCreateTime(new Date());
                                dir2.setStatus(1);
                                dir2.setIsShare(0);
                                dir2.setIcon("文件夹");
                                Dir dirP = null;
                                if (j == 0) {
                                    dirP = dir;
                                } else {
                                    StringBuilder pathP = new StringBuilder(path0);
                                    //找父类的文件路径
                                    for (int k = 0; k <= j - 1; k++) {
                                        //所在路径
                                        if (k - 1 >= 0) {
                                            pathP.append("\\").append(stringPath[k - 1]);
                                        }
                                    }
                                    //新文件夹父类stringPath
                                    dirP = dirService.selectDirPath(pathP.toString(), stringPath[j - 1]);
                                }
                                dir2.setDid(dirP.getId());
                                dir2.setUser(user);
                                //创建目录dir2
                                dirService.addRootDir(dir2);
                                //本地创建
                                File folder = new File(path.toString() + "\\" + stringPath[i]);
                                if (!folder.exists()) {
                                    folder.mkdirs();
                                }
                            }
                            if (i != j) {
                                //完整路径
                                path.append("\\").append(stringPath[j]);
                            }
                        }
                    } else {
                        //最后一个文件】
                        String originalFilename = stringPath[i];

                        String realPath = path0;
                        for (int j = 0; j <= i - 1; j++) {
                            //完整路径
                            realPath += "\\" + stringPath[j];
                        }

                        String newFileNamePrefix = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())
                                + ObjectIdUtil.getObjectId();
                        String fileNameSuffix = "." + FilenameUtils.getExtension(originalFilename);
                        String newFileName = newFileNamePrefix + fileNameSuffix;
                        //日期目录
                        // String dateDirString = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                        //所在目录，将要生成的目录名称

                        //        if (!filePath.exists()) {
                        //            filePath.mkdirs();
                        //        }
                        //抛异常,文件，完整目录
                        File filePathInfo = new File(realPath, newFileName);
                        aa.transferTo(filePathInfo);

                        com.csw.entity.File file = new com.csw.entity.File();
                        file.setId(ObjectIdUtil.getObjectId());
                        file.setName(originalFilename);
                        file.setNewName(newFileName);
                        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                        file.setZFile(suffix);
                        file.setPath(realPath);
                        //
                        double sizes = aa.getSize();
                        String size = null;
                        if (sizes == 0) {
                            size = "1k";
                        }
                        double sizes1 = sizes / 1024;
                        int coutDiv = 1;
                        for (int m = 1; m <= 2; m++) {
                            if (sizes1 > 1024) {
                                coutDiv++;
                                sizes1 = sizes1 / 1024;
                            }
                        }
                        if (coutDiv == 1) {
                            BigDecimal b = new BigDecimal(sizes / 1024);
                            double sz = b.setScale(2, BigDecimal.ROUND_UP).doubleValue();
                            size = sz + "K";
                        } else if (coutDiv == 2) {
                            BigDecimal b = new BigDecimal(sizes / 1024 / 1024);
                            double sz = b.setScale(2, BigDecimal.ROUND_UP).doubleValue();
                            size = sz + "M";
                        } else if (coutDiv == 3) {
                            BigDecimal b = new BigDecimal(sizes / 1024 / 1024);
                            double sz = b.setScale(2, BigDecimal.ROUND_UP).doubleValue();
                            size = sz + "G";
                        }
                        file.setSizes(size);
                        file.setType(aa.getContentType());
                        file.setCreateTime(new Date());
                        file.setOptionTime(new Date());
                        file.setCount(0);
                        file.setStatus(1);
                        String filePath = realPath + "\\" + newFileName;
                        String checkMd5 = MD5Utils.getmd5One(filePath);
                        file.setCheckMd5(checkMd5);
                        file.setIsShare(0);
                        String icon;
                        switch (suffix) {
                            case ".png":
                            case ".jpeg":
                            case ".jpg":
                                icon = "图片";
                                break;
                            case ".zip":
                            case ".rar":
                            case ".7z":
                                icon = "压缩包";
                                break;
                            case ".doc":
                            case ".docx":
                            case ".pdf":
                            case ".txt":
                                icon = "文档";
                                break;
                            default:
                                icon = "其他";
                                break;
                        }
                        file.setIcon(icon);

                        StringBuilder pathP = new StringBuilder(path0);
                        //找父类的文件路径
                        for (int k = 0; k <= stringPath.length - 3; k++) {
                            //所在路径
                            pathP.append("\\").append(stringPath[k]);
                        }
                        Dir dirP = dirService.selectDirPath(pathP.toString(), stringPath[stringPath.length - 2]);
                        file.setDir(dirP);
                        file.setUser(user);
                        //md5
                        List<com.csw.entity.File> filem = fileService.selectFileByPidAndMd5(dirP.getId(), checkMd5);
                        if (filem.size() != 0) {
                            //已有相同文件，不在进行操作
                        } else {
                            //当前文件夹下没有相同的文件
                            fileService.addFile(file);
                        }
                    }

                }
                //文件夹
                        /*文件名//：一级文件夹/1-1.txt
                        文件类型//:text/plain
                        文件大小//:3
                        name//:files
                        后缀//:.txt*/

                        /*文件名//：1.txt
                        文件类型//:text/plain
                        文件大小//:1
                        name//:aa
                        后缀//:.txt*/
            }
            return "redirect:/mydoc/queryOne";

    }

    /**
     * @param bb
     * @param session
     * @return
     */
    @RequestMapping("uploadfile")
    public String upload2(MultipartFile bb, HttpSession session) throws Exception {

            if (bb.getOriginalFilename().equals("")) {
                session.setAttribute("message", "文件是空的");
                return "redirect:/mydoc/queryOne";
            }
            String did = (String) session.getAttribute("did");
            Dir dir = dirService.selectById(did);
            User user = (User) session.getAttribute("user");
            String originalFilename = bb.getOriginalFilename();
            // "后缀//:" + bb.getOriginalFilename().substring(bb.getOriginalFilename().lastIndexOf(".")));
            String realPath = dir.getPath() + "\\" + dir.getName();

            String newFileNamePrefix = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())
                    + ObjectIdUtil.getObjectId();
            String fileNameSuffix = "." + FilenameUtils.getExtension(originalFilename);
            String newFileName = newFileNamePrefix + fileNameSuffix;
       /* //日期目录
        String dateDirString = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //dateDirString//:" + dateDirString);*/
            //所在目录，将要生成的目录名称

//        //dateDir//:" + filePath);
//        if (!filePath.exists()) {
//            filePath.mkdirs();
//        }
            //抛异常,文件，完整目录
            File filePathInfo = new File(realPath, newFileName);
            bb.transferTo(filePathInfo);

            com.csw.entity.File file = new com.csw.entity.File();
            file.setId(ObjectIdUtil.getObjectId());
            file.setName(originalFilename);
            file.setNewName(newFileName);
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            file.setZFile(suffix);
            file.setPath(realPath);
            //
            double sizes = bb.getSize();
            String size = null;
            if (sizes == 0) {
                size = "1k";
            }
            double sizes1 = sizes / 1024;
            int coutDiv = 1;
            for (int m = 1; m <= 2; m++) {
                if (sizes1 > 1024) {
                    coutDiv++;
                    sizes1 = sizes1 / 1024;
                }
            }
            if (coutDiv == 1) {
                BigDecimal b = new BigDecimal(sizes / 1024);
                double sz = b.setScale(2, BigDecimal.ROUND_UP).doubleValue();
                size = sz + "K";
            } else if (coutDiv == 2) {
                BigDecimal b = new BigDecimal(sizes / 1024 / 1024);
                double sz = b.setScale(2, BigDecimal.ROUND_UP).doubleValue();
                size = sz + "M";
            } else if (coutDiv == 3) {
                BigDecimal b = new BigDecimal(sizes / 1024 / 1024);
                double sz = b.setScale(2, BigDecimal.ROUND_UP).doubleValue();
                size = sz + "G";
            }
            file.setSizes(size);
            file.setType(bb.getContentType());
            file.setCreateTime(new Date());
            file.setOptionTime(new Date());
            file.setCount(0);
            file.setStatus(1);
            String filePath = realPath + "\\" + newFileName;
            String checkMd5 = MD5Utils.getmd5One(filePath);
            file.setCheckMd5(checkMd5);
            file.setIsShare(0);
            String icon;
            switch (suffix) {
                case ".png":
                case ".jpeg":
                case ".jpg":
                    icon = "图片";
                    break;
                case ".zip":
                case ".rar":
                case ".7z":
                    icon = "压缩包";
                    break;
                case ".doc":
                case ".docx":
                case ".pdf":
                case ".txt":
                    icon = "文档";
                    break;
                default:
                    icon = "其他";
                    break;
            }
            file.setIcon(icon);

            file.setDir(dir);
            file.setUser(user);
            //md5
            List<com.csw.entity.File> filem = fileService.selectFileByPidAndMd5(dir.getId(), checkMd5);
            if (filem.size() != 0) {
                session.setAttribute("message", "有相同的文件不在上传");
            } else {
                fileService.addFile(file);
            }
            /* fileService.addFile();*/
            return "redirect:/mydoc/queryOne";


    }

    /**
     * @param fileId
     * @param session
     * @return
     */
    @RequestMapping("/del")
    public String del(String fileId, HttpSession session) {

        com.csw.entity.File file = fileService.selectFileById(fileId);
            file.setStatus(0);
            fileService.updateStatus(file);
            session.setAttribute("message", "删除文件成功");
            return "redirect:/mydoc/queryOne";

    }

    /**
     * @param pid
     * @param session
     * @return
     */
    @RequestMapping("/delDir")
    public String delDir(String pid, HttpSession session) {

        Dir dir1 = dirService.selectById(pid);
            dir1.setStatus(0);
            dirService.updateStatue(dir1);
            session.setAttribute("message", "删除文件夹成功");
            return "redirect:/mydoc/queryOne";

    }

    /**
     * @param id
     * @param openStyle
     * @param session
     * @param response
     * @return
     */
    @RequestMapping("down")
    public String down(String id, String openStyle, HttpSession session, HttpServletResponse response) throws Exception {

            String aa = openStyle;
            if (openStyle == null) {
                openStyle = "attachment";
            } else {
                openStyle = "inline";
            }

            com.csw.entity.File file = fileService.selectFileById(id);
            String truePath = file.getPath() + "\\" + file.getNewName();
            File file1 = new File(truePath);
            FileInputStream is = new FileInputStream(file1);
            String fileName = file.getName();
       /* response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        //3.设置content-disposition响应头控制浏览器以下载的形式打开文件
        response.addHeader("Content-Disposition","attachment;filename=" + new String(fileName.getBytes(),"utf-8"));
        //获取文件输入流
        InputStream in = new FileInputStream(truePath);
        int len = 0;
        byte[] buffer = new byte[1024];
        OutputStream out = response.getOutputStream();
        while ((len = in.read(buffer)) > 0) {
            //将缓冲区的数据输出到客户端浏览器
            out.write(buffer,0,len);
        }
        in.close();*/

            response.setHeader("content-disposition", openStyle + ";filename=" + URLEncoder.encode(fileName, "UTF-8"));
            ServletOutputStream os = response.getOutputStream();
            IOUtils.copy(is, os);
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
            //下载成功
            /**
             * 更新次数
             */
            if (aa == null) {
                int newCount = (int) (file.getCount() + 1);
                fileService.updateCount(newCount, file.getId());
            }
            file.setOptionTime(new Date());
            fileService.updateTime(file);
            return null;

    }

    /**
     * @param id
     * @param response
     * @param session
     */
    @RequestMapping("downloadFiles")
    public void batchDownLoadDatumList(String id, HttpServletResponse response, HttpSession session) throws Exception {

            User user = (User) session.getAttribute("user");
            Dir dir = dirService.selectById(id);
//
            String path = dir.getPath() + "\\" + dir.getName();
            String path0 = path.replaceAll("\\\\", "\\\\\\\\\\\\\\\\");
            //找出所有的子目录///
            int status = 1;
            List<com.csw.entity.File> filez = fileService.selectAllFileByFatherFolder(path0, user, status);
            //压缩文件
            List<File> fileList = new ArrayList<>();
            for (com.csw.entity.File f : filez) {
                String srcPath = f.getPath();
                String targetPath = f.getPath();
                File srcFolder = new File(srcPath);
                File tarFolder = new File(targetPath);
                if (!tarFolder.exists()) {
                    tarFolder.mkdirs();
                }

                File srcFile = new File(srcPath + "\\" + f.getNewName());
                InputStream ins = null;
                OutputStream ots = null;

                ins = new FileInputStream(srcFile);
                String nPath = targetPath + "\\" + f.getName();
                ots = new FileOutputStream(nPath);
                int reader = -1;
                byte[] readByte = new byte[2048];
                while ((reader = ins.read(readByte)) != -1) {
                    ots.write(readByte, 0, reader);
                }

                if (ots != null) {
                    ots.close();
                }
                if (ins != null) {
                    ins.close();
                }
                fileList.add(new File(nPath));
            }

            String fileName = dir.getName() + ".zip";
            //在服务器端创建打包下载的临时文件

            String outFilePath = dir.getPath() + "\\" + fileName;
            File file = new File(outFilePath);

            //文件输出流
            String openStyle = "attachment";
            response.setHeader("content-disposition", openStyle + ";filename=" + URLEncoder.encode(fileName, "UTF-8"));
            FileOutputStream outStream = new FileOutputStream(file);
            //压缩流
            ZipOutputStream toClient = new ZipOutputStream(outStream);
            ZipUtils.zipFile(fileList, toClient);
            toClient.close();
            outStream.close();
            ZipUtils.downloadZip(file, response);

    }

    /**
     * @param id
     * @param session
     * @param aa
     * @return
     */
    @RequestMapping("fileYd")
    public String fileYd(String id, HttpSession session, int aa) throws Exception {

            if (id != null) {
                session.setAttribute("fileYdid", id);
                return "redirect:/mydoc/queryOne";
            } else {
                id = (String) session.getAttribute("fileYdid");
                if (aa == 0) {
                    session.setAttribute("fileYdid", null);
                } else if (aa == 1) {
                    com.csw.entity.File file = fileService.selectFileById(id);
                    String did = (String) session.getAttribute("did");
                    Dir dir = dirService.selectById(did);
                    //服务器移动
                    String topath = dir.getPath() + "\\" + dir.getName();
                    File file1 = new File(file.getPath() + "\\" + file.getNewName());
                    String name = file.getNewName();
                    TextCopyFileAndMove.copyFileToDir(topath, file1, name);
                    //服务器移动完成
                    //删除原来的文件
                    //进入删除文件方法


                    if (file1.exists()) {
                        file1.delete();
                    }
                    fileService.deleteFileById(id);
                    //处理完成，
                    //进入处理数据库环节
                    //更新数据
                    file.setPath(topath);
                    file.setDir(dir);
                    User user = (User) session.getAttribute("user");
                    file.setUser(user);
                    //新的的file
                    //md5
                    List<com.csw.entity.File> filem = fileService.selectFileByPidAndMd5(dir.getId(), file.getCheckMd5());
                    if (filem.size() != 0) {
                        session.setAttribute("message", "已有相同文件，请检查后再次进行操作");
                    } else {
                        fileService.addFile(file);
                        session.setAttribute("fileYdid", null);
                        session.setAttribute("message", "文件移动成功");
                    }
                    //"更新成功
                }
                return "redirect:/mydoc/queryOne";
            }

    }

    /**
     * @param id
     * @param session
     * @param aa
     * @return
     */
    @RequestMapping("DirYd")
    public String DirYd(String id, HttpSession session, int aa) throws Exception {

            User user = (User) session.getAttribute("user");
            if (id != null) {
                session.setAttribute("DirYd", id);
                return "redirect:/mydoc/queryOne";
            } else {
                id = (String) session.getAttribute("DirYd");
                if (aa == 0) {
                    session.setAttribute("message", "你已经取消移动");
                    session.setAttribute("DirYd", null);
                } else if (aa == 1) {
                    String did = (String) session.getAttribute("did");
                    //目标文件夹
                    Dir dir = dirService.selectById(did);
                    //要移动的文件夹
                    Dir dir1 = dirService.selectById(id);
                    if (dir.getId().equals(dir1.getDid())) {
                        //有相同目录不移动
                        session.setAttribute("message", "相同目录不进行移动");
                        session.setAttribute("DirYd", null);
                        return "redirect:/mydoc/queryOne";
                    }
                    int status = 1;
                    String patha = dir.getPath() + "\\" + dir.getName();
                    Dir dirSearch = dirService.selectByNamePid(user, status, patha, dir1.getName());
                    if (dirSearch != null) {
                        //同一目录不移动
                        session.setAttribute("message", "同一目录不移动");
                        session.setAttribute("DirYd", null);
                        return "redirect:/mydoc/queryOne";
                    }
                    String path = dir.getPath() + "\\" + dir.getName();
                    String path1 = dir1.getPath() + "\\" + dir1.getName();
                    String path0 = path1.replaceAll("\\\\", "\\\\\\\\\\\\\\\\");


                    //要保证这两个方法都能查到pid,uid
                    //2.查询所有

                    List<com.csw.entity.File> fileList = fileService.selectAllFileByFatherFolder(path0, user, status);
                    for (com.csw.entity.File file : fileList) {
                    }
                    List<Dir> dirList = dirService.selectAllFolderBy(path0, user, status);
                    for (Dir dir2 : dirList) {
                    }
                    dir1.setDid(dir.getId());
                    dirList.add(dir1);

                    //数据库操作
                    //5.数据库复制信息
                    String pathFirst;
                    for (com.csw.entity.File file : fileList) {
                    }
                    for (com.csw.entity.File file : fileList) {
                        pathFirst = dir.getPath() + "\\" + dir.getName();
                        String[] ff = file.getPath().split("\\\\");
                        for (String s : ff) {
                        }

                        boolean judge = false;
                        for (int i = 0; i < ff.length; i++) {
                            //要移动文件夹的名字等于文件路径上的名字
                            if (ff[i].equals(dir1.getName())) {
                                judge = true;
                            }
                            if (judge) {
                                pathFirst += "\\" + ff[i];
                            }
                        }
                        //
                        fileService.deleteFileById(file.getId());
                        //处理完成，
                        //更新数据
                        file.setPath(pathFirst);
                        fileService.addFile(file);
                    }
                    for (Dir dir2 : dirList) {
                    }
                    for (Dir dir2 : dirList) {
                        pathFirst = dir.getPath() + "\\" + dir.getName();
                        String[] ff = dir2.getPath().split("\\\\");
                        boolean judge = false;
                        for (int i = 0; i < ff.length; i++) {
                            if (ff[i].equals(dir1.getName())) {
                                judge = true;
                            }
                            if (judge) {
                                pathFirst += "\\" + ff[i];
                            }
                        }
                        //新路径pathFirst
                        //把原来的文件夹删除
                        dirService.deleteFolderById(dir2.getId());
                        //处理完成，
                        //进入处理数据库环节
                        //更新数据
                        dir2.setPath(pathFirst);

                        //Dir dir3 = dir2;对象是引用数据类型的

                        //【新的的目录2
                        dirService.addRootDir(dir2);

                        //最后
                    }
                    //1.服务器移动
                    TextCopyFileAndMove.copyDir(path, path1);
                    //服务器移动完成

                    //删除原来的文件
                    //进入到删除文件夹方法

                    //找出所有的子目录///
                    List<Dir> targetFolder = dirService.selectAllFolderByFatherFolder(path0, dir1.getId());
                   /* //3..删除原来数据库
                    //删除根目录下的文件
                    fileService.deleteFileByFolderId(dir1.getId());*/
                    //删除子目录下的文件和文件夹
                    for (Dir f : targetFolder) {
                        fileService.deleteFileByFolderId(f.getId());
                        dirService.deleteFolderById(f.getId());
                    }
                   /* //最后删除目标文件夹
                    dirService.deleteFolderById(id);*/
                    File fulldir = new File(path1);
                    //找出所有的子目录///
                    //4.服务器执行删除实际文件夹
                    DeleteAllByPath.deleteFile(fulldir);
                    //删除成功;
                    session.setAttribute("message", "文件夹移动成功");
                }
                session.setAttribute("DirYd", null);
                return "redirect:/mydoc/queryOne";
            }

    }

    /**
     * @param inSearchName
     * @param session
     * @return
     */
    @RequestMapping("inSearch")
    public String inSearch(String inSearchName, HttpSession session) {

        User user = (User) session.getAttribute("user");
            int status = 1;
            String did1 = (String) session.getAttribute("did");
            List<Dir> dirs = dirService.queryAllByinSearchName(inSearchName, user, status);
            List<com.csw.entity.File> files = fileService.queryAllByinSearchName(inSearchName, user, status);

            session.setAttribute("dirs", dirs);
            //图片路径
            List<String> stringList = new ArrayList<>();
            for (com.csw.entity.File file : files) {
                String path = file.getPath() + "\\" + file.getNewName();
                stringList.add(path);
            }
            session.setAttribute("stringList", stringList);

            session.setAttribute("files", files);
            //查询完成
            return "redirect:/jsp/front/main/detail/mydoc.jsp";

    }

    /**
     * @param fileName
     * @param session
     * @param fileId
     * @return
     */
    /*错误提示框，复制，重命名，分享*/
    @RequestMapping("changFileName")
    public String changFileName(String fileName, HttpSession session, String fileId) {

        if (fileId != null) {
                com.csw.entity.File file = fileService.selectFileById(fileId);
                //s.split("\\.")
                session.setAttribute("text_name", file.getName().substring(0, file.getName().lastIndexOf(".")));
                session.setAttribute("changFileName", fileId);
                return "redirect:/mydoc/queryOne";
            } else {
                if (fileName == null || fileName.equals("")) {
                    session.setAttribute("message", "新文件名为空");
                    session.setAttribute("text_name", null);
                    session.setAttribute("changFileName", null);
                } else {
                    //查询
                    fileId = (String) session.getAttribute("changFileName");
                    com.csw.entity.File file = fileService.selectFileById(fileId);
                    String newName = fileName + file.getZFile();
                    file.setName(newName);
                    User user = (User) session.getAttribute("user");
                    int status = 1;
                    //考虑user,status,name,path
                    com.csw.entity.File filenew = fileService.queryByUserStatusNamePath(user, status, file);
                    if (filenew == null) {
                        fileService.updateNameById(file);
                    }
                    file.setOptionTime(new Date());
                    fileService.updateTime(file);
                    session.setAttribute("message", "文件重命名成功");
                }
                session.setAttribute("text_name", null);
                session.setAttribute("changFileName", null);
                return "redirect:/mydoc/queryOne";
            }

    }

    /**
     * @param dirName
     * @param session
     * @param dirId
     * @return
     */
    @RequestMapping("changeDirName")
    public String changeDirName(String dirName, HttpSession session, String dirId) {

        if (dirId != null) {
                Dir dir = dirService.selectById(dirId);
                //s.split("\\.")
                session.setAttribute("text_name2", dir.getName());
                session.setAttribute("changeDirName", dirId);
                return "redirect:/mydoc/queryOne";
            } else {
                if (dirName == null || dirName.equals("")) {
                    session.setAttribute("message", "新文件夹名字为空");
                    session.setAttribute("text_name2", null);
                    session.setAttribute("changeDirName", null);
                } else {
                    //查询
                    dirId = (String) session.getAttribute("changeDirName");
                    Dir dir = dirService.selectById(dirId);
                    String path0 = dir.getPath() + "\\" + dir.getName();
                    String path0_my = path0.replaceAll("\\\\", "\\\\\\\\\\\\\\\\");
                    String[] dirPath = dir.getPath().split("\\\\");
                    int length = dirPath.length;
                    //服务器文件夹重命名
                    //想命名的原文件夹的路径
                    File file1 = new File(path0);
                    //将原文件夹更改为A，其中路径是必要的。注意
                    boolean f = file1.renameTo(new File(dir.getPath() + "\\" + dirName));
                    if (f) {
                        //服务器重命名成功
                    }
                    //
                    dir.setName(dirName);
                    User user = (User) session.getAttribute("user");
                    int status = 1;
                    //考虑user,status,name,path
                    Dir dir1 = dirService.queryByUserStatusNamePath(user, status, dir);
                    dirService.updateNameById(dir);
                    if (dir1 == null) {
                        //更新子文件夹和文件路径
                        List<com.csw.entity.File> fileList = fileService.selectAllFileByFatherFolder(path0_my, user, status);
                        for (com.csw.entity.File file : fileList) {
                            String[] pathfile = file.getPath().split("\\\\");
                            pathfile[length] = dirName;
                            String newFilePath = "";
                            for (int i = 0; i < pathfile.length; i++) {
                                if (i != pathfile.length - 1) {
                                    newFilePath += pathfile[i] + "\\";
                                } else {
                                    newFilePath += pathfile[i];
                                }
                            }
                            file.setPath(newFilePath);
                            fileService.updatePathById(file);
                        }
                        List<Dir> dirList = dirService.selectAllFolderBy(path0_my, user, status);

                        for (Dir dir2 : dirList) {
                            String[] pathDir = dir2.getPath().split("\\\\");
                            pathDir[length] = dirName;
                            String newDirPath = "";
                            for (int i = 0; i < pathDir.length; i++) {
                                if (i != pathDir.length - 1) {
                                    newDirPath += pathDir[i] + "\\";
                                } else {
                                    newDirPath += pathDir[i];
                                }
                            }
                            dir2.setPath(newDirPath);
                            dirService.updatePathById(dir2);
                        }
                        session.setAttribute("message", "文件夹重命名成功");
                    }
                    session.setAttribute("message", "文件夹重命名失败");
                }
                session.setAttribute("text_name2", null);
                session.setAttribute("changeDirName", null);
                return "redirect:/mydoc/queryOne";
            }

    }

    /**
     * @param session
     * @return
     */
    @RequestMapping("getMessage")
    public String getMessage(HttpSession session) {

        String message = (String) session.getAttribute("message");
            return message;

    }

    /**
     * @param session
     * @return
     */
    @RequestMapping("cleMessage")
    public String cleMessage(HttpSession session) {

        session.setAttribute("message", null);
            return "redirect:/mydoc/queryOne";

    }

    /**
     * @param session
     * @param fileId
     * @return
     */
    @RequestMapping("openBefore")
    public String openBefore(HttpSession session, String fileId) {

        com.csw.entity.File file = fileService.selectFileById(fileId);
            String did = file.getDir().getId();
            session.setAttribute("did", did);
            User user = (User) session.getAttribute("user");
            int status = 1;
            List<com.csw.entity.File> files = fileService.queryAllById(did, user, status);
            List<Dir> dirs = dirService.queryAllById(did, user, status);
            session.setAttribute("dirs", dirs);
            session.setAttribute("files", files);
            //查询完成
            return "redirect:/jsp/front/main/detail/mydoc.jsp";

    }

    @RequestMapping("recorverFile")
    public String recorverFile(HttpSession session, String fileId) {

        com.csw.entity.File file = fileService.selectFileById(fileId);
            file.setStatus(1);
            fileService.updateStatus(file);
            return "redirect:/mydoc/queryOne";

    }

    @RequestMapping("recorverDir")
    public String recorverDir(HttpSession session, String pid) {


        Dir dir1 = dirService.selectById(pid);
            dir1.setStatus(1);
            dirService.updateStatue(dir1);
            return "redirect:/mydoc/queryOne";

    }
}
